package com.caifugps.repo;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.caifugps.model.User;

@Transactional
@Repository
public class UserRepo {

	SessionFactory sessionFactory;

	public UserRepo(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	public List<User> findAll() {

		List<User> userList = currentSession().createCriteria(User.class).list();

		return userList;
	}

	public long count() {
		long size = findAll().size();
		return size;
	}

	public User findOne(int id) {

		User user = (User) currentSession().get(User.class, id);
		return user;

	}

	public int findId(String displayname, String password) {
		int id = 0;

		String idHql = "SELECT id FROM User WHERE displayname =:displayname and password =:password";
		Query query = currentSession().createQuery(idHql);
		query.setString("displayname", displayname);
		query.setString("password", password);
		if (query.uniqueResult() != null) {
			id = Integer.parseInt(query.uniqueResult().toString());
		}
		return id;
	}

	public int save(User user) {

		int id = 0;

		id = (Integer) currentSession().save(user);
		return id;

	}
	
	public Boolean validateUser(String displayname, String password) {

		String hPassword = "";
		Boolean returnTag = true;

		String passwordHql = "SELECT password FROM User WHERE displayname = " + "'" + displayname + "'";

		hPassword = currentSession().createQuery(passwordHql).uniqueResult().toString();

		if (password.equals(hPassword)) {
			returnTag = true;
		} else {
			returnTag = false;
		}

		return returnTag;
	}
}
